package models

import (
	"order_srv/basic/config"
	"time"
)

type OrderComment struct {
	Id       int32     `gorm:"column:id;type:int;primaryKey;not null;" json:"id"`
	OrderId  uint32    `gorm:"column:order_id;type:int UNSIGNED;comment:订单id;not null;" json:"order_id"`                           // 订单id
	UserId   uint32    `gorm:"column:user_id;type:int UNSIGNED;comment:用户id;not null;" json:"user_id"`                             // 用户id
	DriverId uint32    `gorm:"column:driver_id;type:int UNSIGNED;comment:司机id;not null;" json:"driver_id"`                         // 司机id
	Start    uint8     `gorm:"column:start;type:tinyint UNSIGNED;comment:评级 1-极度不满意 2-不满意 3-一般 4-满意 5-非常棒;not null;" json:"start"` // 评级 1-极度不满意 2-不满意 3-一般 4-满意 5-非常棒
	Comment  string    `gorm:"column:comment;type:varchar(500);comment:评论;not null;" json:"comment"`                               // 评论
	Tags     string    `gorm:"column:tags;type:varchar(255);comment:评价标签，逗号分隔;default:'';" json:"tags"`                         // 评价标签，逗号分隔
	Images   string    `gorm:"column:images;type:text;comment:评价图片URL，逗号分隔;default:'';" json:"images"`                        // 评价图片URL，逗号分隔
	CreateAt time.Time `gorm:"column:create_at;type:datetime;not null;default:CURRENT_TIMESTAMP;" json:"create_at"`
	UpdateAt time.Time `gorm:"column:update_at;type:datetime;not null;default:CURRENT_TIMESTAMP;" json:"update_at"`
	DeleteAt time.Time `gorm:"column:delete_at;type:datetime;default:NULL;" json:"delete_at"`
}

func (o *OrderComment) TableName() string {
	return "order_comment"
}

// 创建评论
func (o *OrderComment) CreateOrderComment() error {
	return config.DB.Create(&o).Error
}

// 获取乘客对指定司机的评价
func (o *OrderComment) GetOrderCommentByOrder(userId, orderId uint32) error {
	return config.DB.Where("user_id = ? AND order_id = ?", userId, orderId).First(o).Error
}

// 获取司机收到的所有评价
func GetOrderCommentsByDriver(driverId uint32) ([]*OrderComment, error) {
	var comments []*OrderComment
	err := config.DB.Where("driver_id = ?", driverId).Find(&comments).Error
	return comments, err
}

// 获取司机评分
func GetDriverAverageRating(driverId uint32) (float64, error) {
	var avgRating float64
	err := config.DB.Model(&OrderComment{}).Where("driver_id = ?", driverId).Select("AVG(start)").Scan(&avgRating).Error
	return avgRating, err
}
